package com.lcw.lostandfound.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author lcw
 */
@Component
public class UploadUtils {

    @Autowired
    private ObjectMapper obj;

    public String uploadImage(String dir, MultipartFile imgFile) throws Exception {

        List extList=new ArrayList(){{
            this.add("gif");
            this.add("jpg");
            this.add("jpeg");
            this.add("png");
            this.add("bmp");
        }};
        if("image".equals(dir)){
            String SimpleOriginalName=imgFile.getOriginalFilename();
            String fileExt = SimpleOriginalName.substring(SimpleOriginalName.lastIndexOf(".") + 1).toLowerCase();
            if(!extList.contains(fileExt)){
                return getError(1,"上传图片格式错误");//TODO
            }
            if(imgFile.getSize()>10485760){
                return getError(1,"上传图片大小超过限制");
            }
            return getError(0,AliyunUploadDown.picOSS(imgFile));
        }
        return getError(1,"只能上传图片");
    }

    private String getError(Integer error,String message) {
        String ret="";
        Map<String,Object> successMap=new HashMap<>();
        Map<String,Object> errorMap=new HashMap<>();
        if(0==error){
            successMap.put("error",0);
            successMap.put("url",message);
            try{
                ret=obj.writeValueAsString(successMap);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(1==error){
            errorMap.put("error",1);
            errorMap.put("message",message);
            try{
                ret=obj.writeValueAsString(errorMap);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return ret;
    }
}
